#include "edge_zero.h"

#include "edge_laplacian_of_gauss.h"

EdgeZeroCrossing::EdgeZeroCrossing(PNM* img) :
    Convolution(img)
{
}

EdgeZeroCrossing::EdgeZeroCrossing(PNM* img, ImageViewer* iv) :
    Convolution(img, iv)
{
}

double findMax(math::matrix<double> M)
{
	double max = 0;
	int size = M.RowNo();

	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < size; j++)
		{
			if(M(i, j) > max) max = M(i, j);
		}
	}

	return max;
}

double findMin(math::matrix<double> M)
{
	double min = 255;
	int size = M.RowNo();

	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < size; j++)
		{
			if(M(i, j) < min) min = M(i, j);
		}
	}

	return min;
}

PNM* EdgeZeroCrossing::transform()
{
    int width = image->width(),
        height = image->height();



    int    size  = getParameter("size").toInt();
    double sigma = getParameter("sigma").toDouble();
    int    t     = getParameter("threshold").toInt();

    PNM* newImage = new PNM(width, height, QImage::Format_Indexed8);

	auto lgimage = EdgeLaplaceOfGauss(image);

	lgimage.setParameters(size, sigma);

	auto lapimage = lgimage.transform();


	int v_0 = 128;

	for (int i = 0; i < width; i++)
	{
		for (int j = 0; j < height; j++)
		{
			auto r = lgimage.getWindow(i, j, size, Channel::LChannel, Mode::RepeatEdge);
			auto maxr = findMax(r);
			auto minr = findMin(r);

			int pixelr, pixelg, pixelb;

			if(minr < v_0 - t && maxr > v_0 + t) pixelr = qGray(lapimage->pixel(i, j));
			else pixelr = 0;

			newImage->setPixel(i, j, pixelr);

	/*		auto g = lgimage.getWindow(i, j, size, Channel::GChannel, Mode::RepeatEdge);
			auto maxg = findMax(g);
			auto ming = findMin(g);

			if(ming < v_0 - t && maxg > v_0 + t) pixelg = qGreen(lapimage->pixel(i, j));
			else pixelg = 0;

			auto b = lgimage.getWindow(i, j, size, Channel::BChannel, Mode::RepeatEdge);
			auto maxb = findMax(b);
			auto minb = findMin(b);

			if(minb < v_0 - t && maxb > v_0 + t) pixelb = qBlue(lapimage->pixel(i, j));
			else pixelb = 0;
	*/
		}
	}

    return newImage;
}

